package com.zkk.web;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CookieTest extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        boolean flag=false;
        if(cookies!=null){
            for (Cookie cookie : cookies) {
                if(cookie.getName()=="本次登入时间"){
                    flag=true;
                    //把当前时间字符串设置给cookie的值
                    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    String format = simpleDateFormat.format(new Date());
                    String encode = URLEncoder.encode(format, "UTF-8");
                    cookie.setValue(encode);
                    //获取上次保存好的时间，用于响应提醒上次登入时间
                    String value = cookie.getValue();
                    String decode = URLDecoder.decode(value, "UTF-8");
                    //设置相同路径，路径必须和上次相同
                    cookie.setPath("/");
                    cookie.setMaxAge(60*60*24);
                    //添加当前设置好的cookie值
                    resp.addCookie(cookie);
                    //响应到客户端
                    resp.getWriter().println("您上次访问的时间为："+decode);
                }
                }

            }
        if(cookies.length==0 || cookies==null || flag==false){
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String format = simpleDateFormat.format(new Date());
            Cookie cookie=new Cookie(URLEncoder.encode("本次登入时间","UTF-8"),URLEncoder.encode(format,"UTF-8"));
            cookie.setPath("/");
            cookie.setMaxAge(60*60*24*7);
            resp.addCookie(cookie);
            resp.getWriter().println("您是第一次登入，登入时间是："+format);
        }
        }



    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
